//
//  HMStatusPictureView.swift
//  CZWeibo31
//
//  Created by apple on 16/8/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
// cell 可重用标示符
private let HMStatusPictureViewCellId = "HMStatusPictureViewCellId"
// cell 间距 和 宽高
private let margin: CGFloat = 5
private let cellWH: CGFloat = 80
class HMStatusPictureView: UICollectionView {
    // 供外界赋值
    var pictureInfos:[HMPictureInfo]?{
        didSet{
            // 赋值 
            countLabel.text = "\(pictureInfos?.count ?? 0)"
            
            // 得到size
            let size = getPictureViewSize(pictureInfos?.count ?? 0)
            // 更新约束 因为cell 是复用的 但是pictureView的相对约束的对象没有发生改变
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            // 刷新
            reloadData()
        }
    }
    
    // 计算配图的size
    func getPictureViewSize(count: Int) -> CGSize{
        
        // 行数和列数
        let col = count == 4 ? 2 : count > 3 ? 3 : count
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        
        // 计算宽和高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1)*margin
        let h = CGFloat(row) * cellWH + CGFloat(row - 1)*margin
        return CGSize(width: w, height: h)
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.clearColor()
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
        // 注册cell
        registerClass(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureViewCellId)
        // 设置代理
        dataSource = self
        delegate = self
        
        // 设置layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 设置itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直和水平间距
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
    }
    
    
    // MARK: - 懒加载控件
    private lazy var countLabel: UILabel = UILabel(textColor: UIColor.redColor(), textSize: 35)
}

extension HMStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfos?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMStatusPictureViewCellId, forIndexPath: indexPath) as! HMStatusPictureViewCell
        // cell 赋值
        cell.picUrl = pictureInfos![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
//        photoBrowser.delegate = self;
//        photoBrowser.currentImageIndex = indexPath.item;
//        photoBrowser.imageCount = self.modelsArray.count;
//        photoBrowser.sourceImagesContainerView = self.collectionView;
//        
//        [photoBrowser show];
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = pictureInfos!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
}
//MARK: - SDPhotoBrowserDelegate
extension HMStatusPictureView: SDPhotoBrowserDelegate {
    //返回临时占位图片（即原来的小图）
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! HMStatusPictureViewCell
        return cell.bgImageView.image
    }
    // 返回高质量图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlStr = (pictureInfos![index].thumbnail_pic ?? ""  as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
    }

}

// 自定义cell
class HMStatusPictureViewCell: UICollectionViewCell {
    
    // 供外界调用
    var picUrl: HMPictureInfo?{
        didSet{
            bgImageView.hm_setImageWithString(picUrl?.thumbnail_pic, placeholderImgName: "weibo_placeholder")
            // 判断图片的后缀是否是.gif
            if let pic = picUrl?.thumbnail_pic where pic.hasSuffix(".gif") {
                // 显示(cell 复用问题)
                gifImageView.hidden = false
            }else {
                // 隐藏(cell 复用问题)
                gifImageView.hidden = true
            }

        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
         setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        // 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        // 添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.bottom.trailing.equalTo(contentView)
        }
        
    }
    // MARK: - 懒加载控件
    // 背景图片
    private lazy var bgImageView: UIImageView = {
        let img = UIImageView(imgName: "weibo_placeholder")
        img.contentMode = .ScaleAspectFill
        img.clipsToBounds = true
        return img
    }()
    // gif 图片
    private lazy var gifImageView: UIImageView = UIImageView(imgName: "timeline_image_gif")
}







